//
//  SearchFormViewController.m
//  BVCMS Search
//
//  Created by Allen Thomas on 9/13/10.
//

#import "SearchFormViewController.h"
#import "SearchResultsViewController.h"
#import "GenericXMLParser.h"
#import "BVCMSAppDelegate.h"

@implementation SearchFormViewController

@synthesize searchButton, clearButton;
@synthesize table, people, numberOfResults, populateName;

/*
 This action is performed when the view is loaded.  It sets the background image.
 */
-(void)viewDidLoad {
	self.title = @"Search";
	
	UIImage *background = [UIImage imageNamed: @"background.png"];    
	UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; 
	
	[self.view addSubview: imageView];
	[self.view sendSubviewToBack: imageView];
	[imageView release];
		
	table.backgroundColor = [UIColor clearColor];
	
	returnKeyType = UIReturnKeySearch;
	
	firstTitle = @"Name";
	secondTitle = @"Communication";
	thirdTitle = @"Address";
	firstPlaceholder = @"First and/or Last";
	secondPlaceholder = @"Phone or Email";
	thirdPlaceholder = @"Number/Street/City/State";
	
	[super viewDidLoad];
}


/*
 This action is performed when the user clicks the "Clear" button.
 */
-(IBAction)clear:(id)sender
{
	nameField.text = nil;
	commField.text = nil;
	addrField.text = nil;
	[textFieldBeingEdited resignFirstResponder];
}

#pragma mark Search Functions

/* 
 This action is performed when the user clicks the "Search" button
 */
-(IBAction)search:(id)sender
{
	NSLog(@"Search()");
	[textFieldBeingEdited resignFirstResponder];
	
	if([nameField.text length] == 0 && [commField.text length] == 0 && [addrField.text length] == 0 ) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Search Error" message:@"Please fill in at least one search field" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];		
	} else {
		if( people != nil )
			[people release];
		
		BVCMSAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
		
		NSLog(@"building query string");
		NSString *urlString = [NSString stringWithFormat:@"https://%@/iphone/SearchResults?name=%@&comm=%@&addr=%@", delegate.cmsServer, [self getText:nameField], [self getText:commField], [self getText:addrField] ];
		
		urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
			
		NSLog(@"%@", urlString);
		NSURL *url = [NSURL URLWithString:urlString];
		
		HttpConnectionHandler *connectionHandler = [HttpConnectionHandler withURL:url andUsername:delegate.username andPassword:delegate.password];
		
		connectionHandler.errorCallback = @selector(search_error_callback:);
		connectionHandler.callback = @selector(search_callback:);
		connectionHandler.delegate = self;
		[connectionHandler processRequest];
		
		NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"SearchingView" owner:self options:nil];
		if(loadingView) {
			[self.view bringSubviewToFront:loadingView];
		} else {
			loadingView = [nibObjects objectAtIndex:0];
			loadingView.center = CGPointMake(160, 160);
			[self.view addSubview:loadingView];
		}
		
		[searchButton setEnabled:NO];
		[clearButton setEnabled:NO];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	}
}

/*
 Returns the value of the textfield or blank if the value is nil.
 */
-(NSString*)getText:(UITextField*)textField {
	if( textField.text == nil ) {
		return @"";
	} else {
		return textField.text;
	}
}


/*
 This selector is called if the search is successful.
 */
-(void) search_callback:(NSData *)data {
	NSString *output = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	NSLog(@"%@", output);

	[self parseXml:data];
	
	// Stop activity indicator
	[searchButton setEnabled:YES];
	[clearButton setEnabled:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	[self.view sendSubviewToBack:loadingView];
	
	if ([people count] == 0) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"No Results Found" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];
	} else {
		SearchResultsViewController *searchResults = [[SearchResultsViewController alloc]
															  initWithNibName:@"SearchResultsView" bundle:[NSBundle mainBundle]];
		searchResults.title = @"Results";
		searchResults.resultsData = self.people;
		searchResults.numberOfResults = self.numberOfResults;
		
		NSLog(@"loading results");
		[self.navigationController pushViewController:searchResults animated:YES];
		[searchResults release];
	}
	
	[textFieldBeingEdited resignFirstResponder];

	[output release];
}

/*
 This selector is called if the search is unsuccessful.
 */
-(void) search_error_callback:(NSError *)error {
	NSLog(@"Connection failed! Error - %@",
          [error localizedDescription]);
	
	// Stop activity indicator
	[searchButton setEnabled:YES];
	[clearButton setEnabled:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[connectionError show];
	[connectionError release];
}

#pragma mark XML Parsing Methods

/*
 Creates an xml parser and begins parsing the xml data.
 */
-(void) parseXml:(NSData *)data {
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
	
	//Initialize the delegate.
	GenericXMLParser *parser = [[GenericXMLParser alloc] init];
	parser.delegate = self;
	
	//Set delegate
	[xmlParser setDelegate:parser];
	
	//Start parsing the XML file.
	BOOL success = [xmlParser parse];
	
	if(success)
		NSLog(@"No Errors");
	else
		NSLog(@"Error Error Error!!!");
	
	[parser release];
	[xmlParser release];
}

/*
 Callback functions that handles the 'people' tag
 */
-(void) handleElement_SearchResults: (NSDictionary*) attributes {
	NSLog(@"People handler");
	people = [[NSMutableArray alloc] init];
	NSNumber *num = [attributes objectForKey:@"count"];
	numberOfResults = [num intValue];
}

/*
 Callback function that handles the 'person' tag.
 */
-(void) handleElement_Person: (NSDictionary*) attributes {
	NSLog(@"Person handler");

	[people addObject:attributes];
}

#pragma mark - 
#pragma mark Table Delegate Methods
/* 
 This action is triggered when the user selects a row.
 */
- (NSIndexPath *)tableView:(UITableView *)tableView
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
	return nil;
}

#pragma mark Text Field Delegate Methods 
/* 
 This action is triggered when the user begins editing a text field.
 */
- (void)textFieldDidBeginEditing:(UITextField *)textField {
	NSLog(@"begin editing");
	textFieldBeingEdited = textField;
}

/*
 This action is triggered when the user finishes editing a text field.
 */
- (void)textFieldDidEndEditing:(UITextField *)textField {
}


#pragma mark View Background Tap Action
/*
 This action is performed when the user clicks anywhere on the view 
 */
- (IBAction)backgroundTap:(id)sender
{
	[textFieldBeingEdited resignFirstResponder];
}


#pragma mark Table Methods
/*
 This action is performed when the user clicks the done button on the keyboard.
 */
-(IBAction)textFieldDone:(id)sender {
	[sender resignFirstResponder];
	[self search:sender];
}

/*
 Returns the number of sections in the table.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

/*
 Returns the number of rows in the table.
 */
- (NSInteger)tableView:(UITableView *)table
 numberOfRowsInSection:(NSInteger)section {
	return kTotalRows;
}

/*
 Returns a UITableViewCell for a row.
 */
- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
	
	UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
									   reuseIdentifier:SimpleTableIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryNone;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(125, 12, 165, 25)];
		
		switch([indexPath row]) {
			case kNameRowIndex:
				textField.placeholder = firstPlaceholder;
				textField.text = populateName;
				break;
			case kCommunicationRowIndex:
				textField.placeholder = secondPlaceholder;
				break;
			case kAddressRowIndex:
				textField.placeholder	= thirdPlaceholder;
				break;
		}
		
		textField.font = [UIFont systemFontOfSize:15.0];

		textField.adjustsFontSizeToFitWidth = YES;
		textField.textColor = [UIColor colorWithRed:56.0f/255.0f green:84.0f/255.0f blue:135.0f/255.0f alpha:1];
		
		textField.keyboardType = UIKeyboardTypeDefault;
		textField.returnKeyType = returnKeyType;
		textField.clearsOnBeginEditing = NO;
		
		[textField setDelegate:self];
		[textField addTarget:self
							action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
		
		textField.backgroundColor = [UIColor whiteColor];
		textField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
		textField.autocapitalizationType = UITextAutocapitalizationTypeWords; // no auto capitalization support
		textField.textAlignment = UITextAlignmentLeft;
		textField.tag = [indexPath row];
		
		textField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
		[textField setEnabled: YES];
		
		[cell addSubview:textField];
		
		switch([indexPath row]) {
			case kNameRowIndex:
				cell.textLabel.text = firstTitle;
				nameField = textField;
				break;
			case kCommunicationRowIndex:
				cell.textLabel.text = secondTitle;
				commField = textField;
				break;
			case kAddressRowIndex:
				cell.textLabel.text = thirdTitle;
				addrField = textField;
				break;
		}
		
		[textField release];
	}
	
	
	cell.textLabel.font = [UIFont boldSystemFontOfSize:12.0];
	
	return cell;    	
	
}

#pragma mark Memory Management
/*
 Releases allocated memory.
 */
- (void)dealloc {
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	[searchButton release];
	[clearButton release];
	[populateName release];
	[table release];
	[people release];
    [super dealloc];
}


@end
